package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/xhyonline/websocket/server"
	"gopkg.in/olahol/melody.v1"
	"net/http"
	"strings"
)

func main() {
	var s = server.GetServer()
	var port = s.Config.GetStringMapString("websocket")["port"]
	var address = s.Config.GetStringMapString("websocket")["address"]
	go func() {
		s.Socket = melody.New()
		r := gin.Default()
		// 处理 HTTP 协议升级为 websocket
		r.GET("/ws", s.HandleHTTPUpGrade)
		// 处理连接
		s.Socket.HandleConnect(s.HandleConnect)
		// 处理消息
		s.Socket.HandleMessage(s.HandlerMessage)
		// 处理断开连接时间
		s.Socket.HandleClose(s.HandleClose)
		err := r.Run(fmt.Sprintf("0.0.0.0:%s", port))
		if err != nil {
			panic(err)
		}
	}()

	go func() {
		r := gin.Default()
		// 设置静态文件路径
		r.StaticFS("/static", http.Dir("./static/"))
		r.LoadHTMLFiles("static/index.html")
		r.GET("/", func(c *gin.Context) {
			if !IsMobile(c.GetHeader("User-Agent")) {
				c.Header("Content-Type", "text/html; charset=utf-8")
				c.String(200, "<h1>仅支持移动端</h1>")
				return
			}
			c.HTML(200, "index.html", gin.H{
				"port":    port,
				"address": address,
			})
		})
		err := r.Run("0.0.0.0:80")
		if err != nil {
			panic(err)
		}
	}()
	select {}
}
func IsMobile(ua string) bool {
	if len(ua) == 0 {
		return false
	}
	isMobile := false
	mobileKeywords := []string{"Mobile", "Android", "Silk/", "Kindle",
		"BlackBerry", "Opera Mini", "Opera Mobi"}

	for i := 0; i < len(mobileKeywords); i++ {
		if strings.Contains(ua, mobileKeywords[i]) {
			isMobile = true
			break
		}
	}

	return isMobile
}
